(function () {

    var debug = false;
    var lettersToParse = ['A'];

    var pageType;
    var dashCode = '\u2013';

    if ($('.box1:contains(Name)').length &&
        $('.box1:contains(Other names)').length &&
        $('.box1:contains(Origin)').length &&
        $('.box1:contains(Size Type)').length &&
        $('.box1:contains(Breed Group)').length &&
        $('.box1:contains(Name)').length &&
        $('.box1:contains(Other names)').length &&
        $('.box1:contains(Temperament)').length &&
        $('.box1:contains(Height)').length &&
        $('.box1:contains(Weight)').length &&
        $('.box1:contains(Colors)').length &&
        $('.box1:contains(Puppy Price)').length) {
        pageType = 'breed';
        console.log('page type is breed');
    }
    else if ($('th:contains(Image)').length &&
             $('th:contains(Breed)').length &&
             $('th:contains(Classification)').length &&
             $('th:contains(Overview)').length &&
             $('strong:contains(Tags)').length) {
        pageType = 'list';
        console.log('page type is list');
    }

    var listHandler = function () {
        var letter = $('strong:contains(Tags)').text(); 
        letter = letter.substring(letter.indexOf(':') + 1, letter.length).trim();

        var nextLetterHref;

        var alphabetLinks = $('.Middle-r-bk1 a');
        $.each(alphabetLinks, function (index, alphabetLink) {
            if ($(alphabetLink).text() == letter && alphabetLinks.length > index + 1) {
                var nextLetter = $(alphabetLinks[index + 1]).text();
                if ($.inArray(nextLetter, lettersToParse)) {
                    nextLetterHref = $(alphabetLinks[index + 1]).attr('href');
                }
            }
        });

        var nextPageHref;
        var pages = $('.pages li');

        $.each(pages, function (index, link) {
            if ($(link).hasClass('thisclass') && pages.length > index + 1) {
                nextPageHref = $(pages[index + 1]).find('a').attr('href');
            }
        });

        var links = $('.list .img a');
        $.each(links, function (index, link) {
            window.open($(link).attr('href'), '_blank');
        });

        if (nextPageHref) {
             window.open(nextPageHref, '_blank');
        } else if(nextLetterHref) {
             window.open(nextLetterHref, '_blank');
        }
        //window.close();
    };


    var breedHandler = function () {
        var breed = {};
        breed.creatureTypeId = 1;
        breed.name = $('.box1:contains(Name)').next().text().trim();
        breed.otherNames = $('.box1:contains(Other names)').next().text().trim();
        breed.creatureSizeTypeId = getSizeTypeId($('.box1:contains(Size Type)').next().text().trim());
        breed.breedGroupId = getBreedGroupId($('.box1:contains(Breed Group)').next().text().trim());

        var lifeValues = getLifeValues();
        breed.lifeSpanMin = lifeValues.min;
        breed.lifeSpanMax = lifeValues.max;

        var weightValues = getMinMaxWeights();
        breed.weightMaleMin = weightValues.maleMin;
        breed.weightMaleMax = weightValues.maleMax;
        breed.weightFemaleMin = weightValues.femaleMin;
        breed.weightFemaleMax = weightValues.faleMax;

        var heightValues = getMinMaxHeight();
        breed.heightMaleMin = heightValues.maleMin;
        breed.heightMaleMax = heightValues.maleMax;
        breed.heightFemaleMin = heightValues.femaleMin;
        breed.heightFemaleMax = heightValues.faleMax;

        breed.description = getDescription();
        breed.creatureTemperaments = getArrayFromCsv('Temperament');
        breed.creatureColors = getArrayFromCsv('Colors');
        breed.originCountries = $('.box1:contains(Origin)').next().text().trim().replace('or', '').replace(/(\r\n|\n|\r)/gm, "");
        breed.creatureCharacteristics = getCreatureCharacteristics();

        // breed
        $.ajax({
            url: 'http://localhost:7518/api/breeds',
            type: "POST",
            headers: { 'Force-Language': 'en' },
            data: breed
        }).then(function (resp) {
            breed.id = resp.id;

            var imagesArray = $('.info-l').find('.info-img-t img');

            var url = window.location.href;
            var arr = url.split("/");
            url = arr[0] + "//" + arr[2];

            var adultImageSrc = $(imagesArray[0]).attr('src');
            if (debug) {
                adultImageSrc = url + adultImageSrc.substring(1, adultImageSrc.length);
            }

            //var petImageSrc = $(imagesArray[1]).attr('src');
            //if (debug) {
            //    petImageSrc = url + petImageSrc.substring(1, petImageSrc.length);
            //}
            //$.ajax({
            //    url: 'http://localhost:7518/api/breeds/' + breed.id + '/image?imageType=adult',
            //    type: "POST",
            //    headers: { 'Force-Language': 'en' },
            //    data:
            //    {
            //        url: adultImageSrc
            //    }
            //}).then(function (resp) {
            //    $.ajax({
            //        url: 'http://localhost:7518/api/breeds/' + breed.id + '/image?imageType=pet',
            //        type: "POST",
            //        headers: { 'Force-Language': 'en' },
            //        data:
            //        {
            //            url: petImageSrc
            //        }
            //    }).then(function (resp) {
            //        //window.close();
            //    }, function () {
            //        console.log('ERROR');
            //    });
            //}, function () {
            //    console.log('ERROR');
            //});

        }, function () {
            console.log('ERROR');
        });
    };

    function getCreatureCharacteristics() {
        var result = [];

        result.push(getScale12Characteristic(characteristics.GoodWithKids));
        result.push(getScale12Characteristic(characteristics.CatFriendly));
        result.push(getScale12Characteristic(characteristics.DogFriendly));
        result.push(getScale12Characteristic(characteristics.Trainability));
        result.push(getScale12Characteristic(characteristics.Shedding));
        result.push(getScale12Characteristic(characteristics.Watchdog));
        result.push(getScale12Characteristic(characteristics.Intelligence));
        result.push(getScale12Characteristic(characteristics.Grooming));
        result.push(getScale12Characteristic(characteristics.Popularity));
        result.push(getScale12Characteristic(characteristics.Adaptability));

        var hypo =
       {
           id: characteristics.Hypoallergenic.id,
           name: characteristics.Hypoallergenic.name,
           value: 0
       };
        var hypoText = $('.box1:contains(Hypoallergenic)').next().text().trim();
        if (hypoText == 'Yes') {
            hypo.value = 1;
        }

        result.push(hypo);

        return result;
    };

    function getScale12Characteristic(chrctr) {
        var result =
        {
            id: chrctr.id,
            name: chrctr.name,
            value: 0
        };

        var imgs = $('.box1:contains(' + chrctr.name + ')').next().find('img');

        imgs.each(function (index, entry) {
            var src = $(entry).attr('src');

            var val = 0;
            if (src.indexOf('star01.gif') > 0) {
                val = 2;
            } else if (src.indexOf('star02.gif') > 0) {
                val = 0;
            } else if (src.indexOf('star03.gif') > 0) {
                val = 1;
            }

            result.value += val;
        });

        var additionalText = $('.box1:contains(' + chrctr.name + ')').next().text().trim();

        switch (additionalText) {
            case 'Best !':
            case 'Very friendly!':
                result.value += 1;
                break;
        }

        return result;
    }


    function capitaliseFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    var getArrayFromCsv = function (field) {
        var text = $('.box1:contains(' + field + ')').next().text().trim().replace('or', '').replace(/(\r\n|\n|\r)/gm, "");

        var raws = text.split(',');

        var results = [];
        for (var i = 0; i < raws.length; i++) {
            results.push({
                name: capitaliseFirstLetter(raws[i].trim())
            });
        }

        return results;
    };

    var getLifeValues = function () {
        var text = $('.box1:contains(Life span)').next().text().trim().replace(/ /g, '').replace(/(\r\n|\n|\r)/gm, "");
        var measureName = 'years';
        var result = {};
        var dashCode = '-';

        result.min = text.substring(0, text.indexOf(dashCode));
        result.max = text.substring(text.indexOf(dashCode) + 1, text.indexOf(measureName));

        return result;
    };

    var getMinMaxWeights = function () {
        var parameterName = 'Weight';
        var measureName = 'kg';

        var text = $('.box1:contains(' + parameterName + ')').next().text().trim().replace(/ /g, '').replace(/(\r\n|\n|\r)/gm, "");
        var malePart = text.substring(0, text.indexOf(measureName) + 2);
        var femalePart = text.substring(malePart.length, text.length);


        var result = {};
        //parse male
        result.maleMin = malePart.substring(5, malePart.indexOf(dashCode));
        result.maleMax = malePart.substring(malePart.indexOf(dashCode) + 1, malePart.indexOf(measureName));
        result.femaleMin = femalePart.substring(7, femalePart.indexOf(dashCode));
        result.faleMax = femalePart.substring(femalePart.indexOf(dashCode) + 1, femalePart.indexOf(measureName));

        return result;
    };

    var getMinMaxHeight = function () {
        var parameterName = 'Height';
        var measureName = 'cm';
        var inches = 'inches(';
        var cm = 'cm';
        var femaleStart;

        var text = $('.box1:contains(' + parameterName + ')').next().text().trim().replace(/ /g, '').replace(/(\r\n|\n|\r)/gm, "");
        var malePart = text.substring(0, text.indexOf(measureName) + 2);
        femaleStart = malePart.length;
        malePart = malePart.substring(malePart.indexOf(inches) + inches.length, malePart.indexOf(cm));

        var femalePart = text.substring(femaleStart, text.length);
        femalePart = femalePart.substring(femalePart.indexOf(inches) + inches.length, femalePart.indexOf(cm));

        var result = {};
        //parse male
        result.maleMin = malePart.substring(0, malePart.indexOf(dashCode));
        result.maleMax = malePart.substring(malePart.indexOf(dashCode) + 1, malePart.length);
        result.femaleMin = femalePart.substring(0, femalePart.indexOf(dashCode));
        result.faleMax = femalePart.substring(femalePart.indexOf(dashCode) + 1, femalePart.length);

        return result;
    };

    var getDescription = function () {
        var description = 'Overview. ' + $('th:contains(Overview)').parent().next().text().trim();
        description += 'Body type. ' + $('th:contains(Body type)').parent().next().text().trim();
        description += 'Coat. ' + $('th:contains(Coat)').parent().next().text().trim();
        description += 'Color. ' + $('th:contains(Color)').parent().next().text().trim();
        description += 'Temperament. ' + $('th:contains(Temperament)').parent().next().text().trim();
        description += 'Tasty Tidbits. ' + $('th:contains(Tasty Tidbits)').parent().next().text().trim();
        return description;
    };

    var getSizeTypeId = function (sizeType) {
        if (sizeType.toLowerCase().indexOf("small") >= 0) {
            return 1;
        } else if (sizeType.toLowerCase().indexOf("medium") >= 0) {
            return 2;
        } else if (sizeType.toLowerCase().indexOf("large") >= 0) {
            return 3;
        } else if (sizeType.toLowerCase().indexOf("giant") >= 0) {
            return 4;
        } else {
            throw new Error('unexpected');
        }
    };

    var getBreedGroupId = function (breedGroup) {
        if (breedGroup.toLowerCase().indexOf("toy") >= 0) {
            return 1;
        } else if (breedGroup.toLowerCase().indexOf("sporting") >= 0) {
            return 2;
        } else if (breedGroup.toLowerCase().indexOf("hound") >= 0) {
            return 3;
        } else if (breedGroup.toLowerCase().indexOf("hound") >= 0) {
            return 4;
        } else if (breedGroup.toLowerCase().indexOf("working") >= 0) {
            return 5;
        } else if (breedGroup.toLowerCase().indexOf("herding") >= 0) {
            return 6;
        } else {
            throw new Error('unexpected');
        }
    };

    var characteristics =
{
    GoodWithKids: {
        id: 1, name: 'Good with Kids'
    },
    CatFriendly: {
        id: 2, name: 'Cat Friendly'
    },
    DogFriendly: {
        id: 3, name: 'Dog Friendly'
    },
    Trainability: {
        id: 4, name: 'Trainability'
    },
    Shedding: {
        id: 5, name: 'Shedding'
    },
    Watchdog: {
        id: 6, name: 'Watchdog'
    },
    Intelligence: {
        id: 7, name: 'Intelligence'
    },
    Grooming: {
        id: 8, name: 'Grooming'
    },
    Popularity: {
        id: 9, name: 'Popularity'
    },
    Adaptability: {
        id: 10, name: 'Adaptability'
    },
    Hypoallergenic: {
        id: 11, name: 'Hypoallergenic'
    },
    Guard: {
        id: 12, name: ''
    },
    Flutty: {
        id: 13, name: ''
    },
    LowShadding: {
        id: 14, name: ''
    }
};


    switch (pageType) {
        case 'breed':
            breedHandler();
            break;
        case 'list':
            listHandler();
            break;
    }
})();


